<?php

namespace STAGE\StageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use STAGE\UserBundle\Entity\user;
use STAGE\StageBundle\Form\EtudiantType;
use Symfony\Component\HttpFoundation\Response;

class EtudiantController extends Controller {

    public function indexAction() {
        return $this->render('StageBundle: Etudiant:index.html.twig');
    }

    public function newAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();
        $id = $request->get('id');
       
         if ($id == '')
             $etudiant = new User();
         else
            $etudiant = $em->getRepository('UserBundle:User')->find($id);
        $form = $this->createForm(new EtudiantType(), $etudiant);
        if ($request->isMethod('post')) {
            $form->bind($request);
//            if($form->isValid()){
            $etudiant = $form->getData();
            $etudiant->addRole('ROLE_ETUDIANT');
            $etudiant->setEnabled(true);
            $em->persist($etudiant);
            $em->flush();
            $url = $this->generateUrl('stage_etudiant_list');
            return $this->redirect($url);
//            }
        }
        return $this->render('StageBundle:Etudiant:new.html.twig', array('id' => $id, 'form' => $form->createView()));
    }

    public function listAction() {
        $em = $this->getDoctrine()->getManager();
        $request = $this->getRequest();
        $type = $request->get('type');
        $etudiants = $em->getRepository('UserBundle:User')->getEtudiant();
        if ($type != '') {
            return $this->render('StageBundle:Etudiant:page_list.html.twig', array('etudiants' => $etudiants));
        }
        return $this->render('StageBundle:Etudiant:list.html.twig', array('etudiants' => $etudiants));
    }

    public function deleteAction() {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();
        $id = $request->get('id');
        $etudiant = $em->getRepository('UserBundle:User')->find($id);
        $em->remove($etudiant);
        $em->flush();
        $url = $this->generateUrl('stage_etudiant_list', array('type' => 'ajax'));
        return $this->redirect($url);
    }

}
